import os
from pathlib import Path
import re
import shutil
import subprocess

################################修改类名################################                    
def rewrite_file(old_file_path, new_file_path):
    """
    重写文件 即copy 文件新建
    """
    if not os.path.exists(old_file_path): return
    if not new_file_path.startswith('/'):
        new_file_path = '/' + new_file_path
    with open(old_file_path, "rb") as fr:
        content = fr.read()
        try:
            with open(new_file_path, "wb") as fw:
                fw.write(content)
        except FileNotFoundError:
            directory = os.path.dirname(new_file_path)
            os.makedirs(directory)
            with open(new_file_path, "wb") as fw:
                fw.write(content)
            
def rename_file(old_file_path, new_file_path):
    """
    重命名文件
    """
    if not os.path.exists(old_file_path): return
    if not new_file_path.startswith('/'):
        new_file_path = '/' + new_file_path
    old_file_name = Path(old_file_path).name
    new_file_name = Path(new_file_path).name
    # 处理 Objective-C 文件
    if old_file_name.endswith(".h") or old_file_name.endswith(".m") or old_file_name.endswith(".mm") or old_file_name.endswith(".swift"):
        with open(old_file_path, "r", encoding="utf-8") as f:
            content = f.read()
        # 替换类名
        old_class_name = old_file_name.split(".")[0]
        new_class_name = new_file_name.split(".")[0]
        new_content = re.sub(r'\b' + old_class_name + r'\b', new_class_name, content)
        # 则写文件到新的路径
        try:
            with open(new_file_path, "w", encoding="utf-8") as f:
                f.write(new_content)
        except FileNotFoundError:
            directory = os.path.dirname(new_file_path)
            os.makedirs(directory)
            with open(new_file_path, "w", encoding="utf-8") as f:
                f.write(new_content)
            
def traverse_iOS_files_rename(directory, is_rename=True, pre_name="QA", need_rename_pre_name=None):
    """
    循环修改类名
    类文件所在文件夹
    """
    path = Path(directory)
    copy_path = path.parent / (path.name + "_renames")
    if not copy_path.exists():
        copy_path.mkdir(parents=True, exist_ok=True)
    #print(copy_path)
    for item in path.rglob("*"):
        if item.name.startswith("."):
            continue
        if item.is_file():
            old_file_path = item.resolve().as_posix()
            new_file_path = (copy_path / item.relative_to(path)).as_posix()
                
            print(new_file_path)
            if (is_rename):
                if not item.name.endswith(".h") and not item.name.endswith(".m") and not item.name.endswith(".mm") and not item.name.endswith(".swift"):
                    rewrite_file(old_file_path, new_file_path)
                    continue
                
                if item.name.startswith(pre_name):
                    continue
                
                new_name = Path(new_file_path).name
                
                if (need_rename_pre_name != None):
                    if (new_name.startswith(need_rename_pre_name)):
                        new_name = new_name.replace(need_rename_pre_name, pre_name)
                    elif ('+' + need_rename_pre_name in new_name):
                        new_name = new_name.replace('+' + need_rename_pre_name, '+' + pre_name)                
                elif (new_name.startswith("MP")):
                    new_name = new_name.replace("MP", pre_name)
                elif (new_name.startswith("MO")):
                    new_name = new_name.replace("MO", pre_name)
                elif (new_name.startswith("CG")):
                    new_name = new_name.replace("CG", pre_name)
                elif (new_name.startswith("IC")):
                    new_name = new_name.replace("IC", pre_name)
                elif (new_name.startswith("Mz")):
                    new_name = new_name.replace("Mz", pre_name)
                elif (new_name.startswith("MW")):
                    new_name = new_name.replace("MW", pre_name)
                elif "+MP" in new_name:
                    new_name = new_name.replace("+MP", pre_name)
                elif "+MO" in new_name:
                    new_name = new_name.replace("+MO", pre_name)
                elif "+GX" in new_name:
                    new_name = new_name.replace("+GX", pre_name)
                elif "+WL" in new_name:
                    new_name = new_name.replace("+WL", pre_name)
                elif "+" in new_name:
                    new_name = new_name.replace("+", pre_name)
                else:
                    new_name = pre_name + new_name
                
                new_file_path = (Path(new_file_path).parent / new_name).as_posix()
                rename_file(old_file_path, new_file_path)
            else:
                rewrite_file(old_file_path, new_file_path)
        else:
            new_file_path = (copy_path / item.relative_to(path))
            if not new_file_path.exists():
                new_file_path.mkdir(parents=True, exist_ok=True)
            pass
    

################################图片压缩################################
def compress_image(input_path, output_path, quality=95):
    """
    压缩图片
    :param input_path: 输入图片路径
    :param output_path: 输出图片路径
    :param quality: 压缩质量,取值范围为0-100,默认为95
    """ 
    try:
        # 使用 pngquant 压缩图片
        command = ["pngquant", "--force", "--output", output_path, "--quality", "60-99", input_path]
        subprocess.run(command, check=True)
        
        print(f"图片已压缩并保存到 {output_path}")
    except Exception as e:
        print(f"压缩图片时出错: {e}")

def traverse_compress_image(directory):
    """
    循环压缩图片
    图片所在文件夹
    """
    path = Path(directory)
    copy_path = path.parent / (path.name + "_copy")
    if not copy_path.exists():
        copy_path.mkdir(parents=True, exist_ok=True)
    #print(copy_path)
    for item in path.rglob("*"):
        if item.name.startswith("."):
            continue
        if item.is_file():
            # print("文件"+item.name)
            old_file_path = item.resolve().as_posix()
            new_file_path = (copy_path / item.relative_to(path)).as_posix()
            #print(new_file_path)
            if item.name.endswith(".png") or item.name.endswith(".jpg") or item.name.endswith(".jpeg"):
                compress_image(old_file_path, new_file_path)
            else:
                rewrite_file(old_file_path, new_file_path)
        else:
            #print("文件夹"+item.name)
            new_file_path = (copy_path / item.relative_to(path))
            if not new_file_path.exists():
                new_file_path.mkdir(parents=True, exist_ok=True)
            pass

if __name__ == "__main__":
    
    project_directory = "/Users/mac/Documents/cfwifine/python/FlaskProj/utils/classes"
    
    #压缩图片
    # traverse_compress_image(project_directory)
    
    #修改类名
    traverse_iOS_files_rename(project_directory, is_rename=True, pre_name="WCI", need_rename_pre_name="MO")
    
    # dir = "/Users/mac/Documents/cfwifine/python/FlaskProj/utils/classes/QAXinFiles/MOPro"
    # path = Path(dir)
    # for item in path.rglob("*.h"):
    #     print(item, 'isFile:{0}', item.is_file())
    # list = list(path.rglob("*.h"))
    # print(list)
    
    # path = Path('/Users/mac/Documents/cfwifine/python/FlaskProj/utils/test/QAAppDelegate.m')
    # with open(path, "r", encoding="utf-8") as f:
    #     content = f.read()
    #     print(content)
    
    # newcontent = re.sub(r'\b' + 'QAIMDatabase' + r'\b', 'MPIMDatabase', content)
    # print(newcontent)
    
    pass